package org.example.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.example.bean.R;
import org.example.entity.Users;
import org.example.service.UsersService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
@RequestMapping("/api/login")
@RequiredArgsConstructor
public class WxLoginController {

    private final RestTemplate restTemplate = new RestTemplate();
    private final UsersService usersService;

    @PostMapping("/wx")
    public R wxLogin(@RequestBody Map<String, String> body) throws Exception {
        String code = body.get("code");
        String nickname = body.get("nickname");
        String avatar = body.get("avatar");

        String url = "https://api.weixin.qq.com/sns/jscode2session" +
                "?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String respStr = restTemplate.getForObject(url, String.class,
                "wx29223b50aaa4f2b8",
                "9eaa14c0528be8ad1878d9c7474c481d",
                code);

        Map<String, Object> wx = new ObjectMapper().readValue(respStr, Map.class);
        if (wx.containsKey("errcode")) {
            return new R().setCode(500).setMsg("微信校验失败: " + wx.get("errmsg"));
        }

        String openid = (String) wx.get("openid");
        String unionid = (String) wx.get("unionid");

        // 保存或更新用户信息
        Users user = usersService.saveOrUpdateUser(openid, unionid, nickname, avatar);
        
        return new R()
                .add("openid", openid)
                .add("user", user)
                .setMsg("登录成功");
    }
}